// Copyright (C) 2005 Taylor L. Riché <riche@cs.utexas.edu>
//  
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software 
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// 	$Id: TraceInterface.cc 102 2005-08-02 17:49:21Z richetl $	
//

#include "TraceInterface.hh"

using namespace lee;

TraceInterface::TraceInterface(std::string intf, 
			       std::string fn, 
			       TraceType t,
			       int n) : NetInterface(intf),
					filename(fn),
					type(t),
					numPkts(n)
{
  if(type == PCAP) {
    reader = new tt::PcapReader(filename);
    writer = new tt::PcapWriter(filename + "OUT");
  }
  else if(type == TSH) {
    reader = new tt::TshReader(filename);
    writer = new tt::TshWriter(filename + "OUT");
  }
  MethodWrapper<TraceInterface> * mw = new MethodWrapper<TraceInterface>;
  mw->object = this;
  mw->method = &TraceInterface::process;
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  if(pthread_create(&coreThread, &attr, plainFunctionNI, (void *)mw)) {
    std::cerr << "pthread_create failed" << std::endl;
    std::exit(1);
  }
}

void
TraceInterface::process()
{
  Synchronized::Scope mutex(this);
  while((ag == NULL) || (scheduler == NULL)) {
    wait();
  }
  for(int i = 0; i < numPkts; ++i) {
    // enqueue packets
    tt::Packet * pkt = new tt::Packet();
    reader->readPacket(*pkt);
    PCon * newPCon = new PCon();
    newPCon->setPPFunction(ag->getNextPPFunction(intfName, IN));
    newPCon->setPacket(static_cast<PktData *>(pkt));
    ProcUnit * nextProc = scheduler->getProcUnit(newPCon);
    nextProc->executePCon(newPCon);
  }
  pthread_cancel(coreThread);
}
